using B.S.Database.Domain.Entity;
using B.S.Database.ErrorCode;
using B.S.Database.Interface.Interface;
using B.S.Database.Write.Api.Application.Commands.Image;
using B.S.Database.Write.Api.SysConfig;
using MediatR;
using Microsoft.Extensions.Options;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System.Reflection;

namespace B.S.Database.Write.Api.Application.CommandHandler.Image
{
    public class PictureDeleteCommandHandler : IRequestHandler<PictureDeleteCommands, Apiresult<object>>
    {
        private readonly IBaseResotity<Picture_Information> _pictureRepository;
        private readonly IOptions<QiNiuConfig> _qiniuConfig;
        private readonly ILogger<PictureDeleteCommandHandler> _logger;

        public PictureDeleteCommandHandler(
            IBaseResotity<Picture_Information> pictureRepository,
            IOptions<QiNiuConfig> qiniuConfig,
            ILogger<PictureDeleteCommandHandler> logger)
        {
            _pictureRepository = pictureRepository;
            _qiniuConfig = qiniuConfig;
            _logger = logger;
        }

        public async Task<Apiresult<object>> Handle(PictureDeleteCommands request, CancellationToken cancellationToken)
        {
            var result = new Apiresult<object>();

            try
            {
                // 验证请求
                if (request.TraceabilityId <= 0)
                {
                    result.Code = ApiEnums.失败;
                    result.Message = "溯源ID不能为空";
                    return result;
                }

                if (string.IsNullOrEmpty(request.ImageType))
                {
                    result.Code = ApiEnums.失败;
                    result.Message = "图片类型不能为空";
                    return result;
                }

                // 验证图片类型
                if (!IsValidImageType(request.ImageType))
                {
                    result.Code = ApiEnums.失败;
                    result.Message = "无效的图片类型";
                    return result;
                }

                // 查找数据库记录
                var existingPicture = _pictureRepository.GetAll().FirstOrDefault(x => x.TraceabilityId == request.TraceabilityId);
                if (existingPicture == null)
                {
                    result.Code = ApiEnums.失败;
                    result.Message = "未找到对应的图片记录";
                    return result;
                }

                // 获取当前字段的图片URL
                var currentUrls = GetPropertyValue(existingPicture, request.ImageType);
                if (string.IsNullOrEmpty(currentUrls))
                {
                    result.Code = ApiEnums.失败;
                    result.Message = "该字段没有图片数据";
                    return result;
                }

                var urlList = currentUrls.Split(request.Separator, StringSplitOptions.RemoveEmptyEntries).ToList();
                var deletedUrls = new List<string>();
                var remainingUrls = new List<string>();

                if (request.ImageIndex.HasValue)
                {
                    // 按索引删除图片
                    int index = request.ImageIndex.Value;
                    if (index >= 0 && index < urlList.Count)
                    {
                        deletedUrls.Add(urlList[index]);
                        remainingUrls = urlList.Where((url, i) => i != index).ToList();
                    }
                    else
                    {
                        result.Code = ApiEnums.失败;
                        result.Message = $"图片索引 {index} 超出范围，当前共有 {urlList.Count} 张图片";
                        return result;
                    }
                }
                else if (!string.IsNullOrEmpty(request.ImageUrl))
                {
                    // 删除指定的图片URL
                    if (urlList.Contains(request.ImageUrl))
                    {
                        deletedUrls.Add(request.ImageUrl);
                        remainingUrls = urlList.Where(url => url != request.ImageUrl).ToList();
                    }
                    else
                    {
                        result.Code = ApiEnums.失败;
                        result.Message = "未找到指定的图片URL";
                        return result;
                    }
                }
                else
                {
                    // 删除该字段的所有图片
                    deletedUrls = urlList.ToList();
                    remainingUrls = new List<string>();
                }

                // 删除七牛云上的文件
                if (request.DeleteFromQiniu && deletedUrls.Any())
                {
                    await DeleteFromQiniu(deletedUrls);
                }

                // 更新数据库
                var newValue = string.Join(request.Separator, remainingUrls);
                SetPropertyValue(existingPicture, request.ImageType, newValue);
                _pictureRepository.Update(existingPicture);

                result.Code = ApiEnums.成功;
                result.Message = $"成功删除 {deletedUrls.Count} 张图片";
                result.Data = new
                {
                    DeletedUrls = deletedUrls,
                    RemainingUrls = remainingUrls,
                    TraceabilityId = request.TraceabilityId,
                    ImageType = request.ImageType
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "图片删除过程中发生错误");
                result.Code = ApiEnums.失败;
                result.Message = $"图片删除失败: {ex.Message}";
            }

            return result;
        }

        /// <summary>
        /// 从七牛云删除文件
        /// </summary>
        private async Task DeleteFromQiniu(List<string> urls)
        {
            try
            {
                var config = _qiniuConfig.Value;
                if (string.IsNullOrEmpty(config.AccessKey) || string.IsNullOrEmpty(config.SecretKey) || string.IsNullOrEmpty(config.Bucket))
                {
                    _logger.LogWarning("七牛云配置不完整，跳过文件删除");
                    return;
                }

                var mac = new Mac(config.AccessKey, config.SecretKey);
                var bucketManager = new BucketManager(mac, new Config());

                foreach (var url in urls)
                {
                    try
                    {
                        // 从URL中提取文件key
                        var key = ExtractKeyFromUrl(url, config.BaseUrl);
                        if (!string.IsNullOrEmpty(key))
                        {
                            var deleteResult = bucketManager.Delete(config.Bucket, key);
                            if (deleteResult.Code == 200)
                            {
                                _logger.LogInformation($"成功删除七牛云文件: {key}");
                            }
                            else
                            {
                                _logger.LogWarning($"删除七牛云文件失败: {key}, Code: {deleteResult.Code}, Text: {deleteResult.Text}");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"删除七牛云文件时发生错误: {url}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除七牛云文件过程中发生错误");
            }
        }

        /// <summary>
        /// 从URL中提取文件key
        /// </summary>
        private string ExtractKeyFromUrl(string url, string baseUrl)
        {
            try
            {
                if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(baseUrl))
                    return string.Empty;

                var trimmedBaseUrl = baseUrl.TrimEnd('/');
                if (url.StartsWith(trimmedBaseUrl))
                {
                    return url.Substring(trimmedBaseUrl.Length + 1); // +1 for the '/'
                }

                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 验证图片类型是否有效
        /// </summary>
        private bool IsValidImageType(string imageType)
        {
            var validTypes = new[]
            {
                "Inspection_Repor",
                "Livestock_Certification",
                "Certification_Documents",
                "Food_Safety",
                "Raw_Material",
                "Auxiliary_Materials",
                "Additive_Materials",
                "Packaging_Materials",
                "Enterprise_Image"
            };

            return validTypes.Contains(imageType);
        }

        /// <summary>
        /// 获取属性值
        /// </summary>
        private string GetPropertyValue(Picture_Information picture, string propertyName)
        {
            var property = typeof(Picture_Information).GetProperty(propertyName);
            return property?.GetValue(picture)?.ToString() ?? "";
        }

        /// <summary>
        /// 设置属性值
        /// </summary>
        private void SetPropertyValue(Picture_Information picture, string propertyName, string value)
        {
            var property = typeof(Picture_Information).GetProperty(propertyName);
            property?.SetValue(picture, value);
        }
    }
} 